package me.khrystal.store.utils;

import android.app.Activity;
import android.content.ClipDescription;
import android.content.Context;
import android.text.ClipboardManager;
import android.text.TextUtils;

/**
 * usage:
 * author: kHRYSTAL
 * create time: 17/7/15
 * update time:
 * email: 723526676@qq.com
 */

public class StringUtil {

    /**
     * 判断字符串为空
     */
    public static boolean isNullOrEmpty(String s) {
        return s == null || s.equals("");
    }

    /**
     * 两个字符串是否相同
     */
    public static boolean isEquals(String s1, String s2) {
        if (StringUtil.isNullOrEmpty(s1)) {
            if (StringUtil.isNullOrEmpty(s2)) {
                return true;
            } else {
                return false;
            }
        } else {
            return s1.equals(s2);
        }
    }

    /**
     * 判断单个字符是否为中文
     */
    public static boolean isChinese(String c) {
        String chinese = "[\u4e00-\u9fa5]";
        return c.matches(chinese);
    }

    /**
     * 获取字符数，英文占1个中文占2个
     */
    public static int getLength(String str) {
        int valueLength = 0;
        try {
            String chinese = "[\u4e00-\u9fa5]";
            for (int i = 0; i < str.length(); i++) {
                String temp = str.substring(i, i + 1);
                if (temp.matches(chinese)) {
                    valueLength += 2;
                } else {
                    valueLength += 1;
                }
            }
            return valueLength;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 复制文本到剪贴板
     */
    public static void copyToClipboard(Context context, String text) {
        ClipboardManager cmb = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(text);
    }

    /**
     * 获取剪切板文字
     */
    public static String getClipText(Context context) {
        android.content.ClipboardManager myClipboard = (android.content.ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
        if (myClipboard.hasPrimaryClip()) {
            if (myClipboard.getPrimaryClipDescription().hasMimeType(
                    ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                CharSequence cs = myClipboard.getPrimaryClip().getItemAt(0).getText();
                if (cs != null) {
                    return cs.toString();
                }
            }
        }
        return null;
    }

    /**
     * 去掉中间多余的空格与左右空格
     */
    public static String replaceMoreSpace(String string) {
        if (!TextUtils.isEmpty(string)) {
            string = string.trim();
            String temp = string.replaceAll("\\s{1,}", " ");
            return temp;
        }
        return null;
    }
}
